package model

import (
	"errors"
	"github.com/jinzhu/gorm"
)

// DatasetInfo represents a Dataset info
type DatasetInfo struct {
	gorm.Model
	Name     string `json:"name"`
	FilePath string `json:"file_path"`
	UserID   int64  `json:"user_id"`
	Type     int64  `json:"type"`
}

// AddNewDataset add a new Dataset
func AddNewDataset(cameraInfo *DatasetInfo) (interface{}, error) {
	camera := db.Save(cameraInfo)
	return camera.Value, nil
}

// ExistDatasetByName check the Dataset name is exist or not
func ExistDatasetByName(name string) bool {
	var Dataset DatasetInfo
	db.Select("id").Where("name = ?", name).First(&Dataset)
	if Dataset.ID > 0 {
		return true
	}
	return false
}

// GetDataset get a single Dataset
func GetDataset(DatasetID string) (*DatasetInfo, error) {
	var Dataset DatasetInfo
	// SELECT * FROM Dataset WHERE id = DatasetID;
	db.First(&Dataset, DatasetID)
	if Dataset.ID == 0 {
		err := errors.New("no Dataset found")
		return &DatasetInfo{}, err
	}

	return &Dataset, nil
}

func GetDatasetByType(DType string) ([]DatasetInfo, error) {
	var myDataset []DatasetInfo
	db.Where("type = ?", DType).Find(&myDataset)
	if len(myDataset) == 0 {
		err := errors.New("no dataset found")
		return []DatasetInfo{}, err
	}
	return myDataset, nil
}

// ExistDatasetByID check the id is exist or not
func ExistDatasetByID(ID int) bool {
	var myDataset DatasetInfo
	db.Select("id").Where("id = ?", ID).First(&myDataset)
	if myDataset.ID > 0 {
		return true
	}
	return false
}

// UpdateDataset edit user info
func UpdateDataset(id int, data interface{}) bool {
	db.Model(&DatasetInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteDataset delete the user info from db
func DeleteDataset(id int) bool {
	db.Where("id = ?", id).Delete(&DatasetInfo{})

	return true
}

// GetAllDatasets get the all Datasets info from db
func GetAllDatasets() (result []DatasetInfo, err error) {
	var myDataset []DatasetInfo
	db.Find(&myDataset)

	if len(myDataset) == 0 {
		err = errors.New("no Dataset found")
		return nil, err
	}
	return myDataset, nil
}
